package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.SystemConfigMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * @description: ${description}
 * @author: cuicui
 **/
@Service
public class SystemConfigServiceImpl implements SystemConfigService {

    @Autowired
    SystemConfigMapper systemConfigMapper;

    @Override
    public void configMall(ConfigMall configMall) throws IllegalAccessException {
        config(configMall);
    }

    @Override
    public ConfigMall showMallConfig() throws IllegalAccessException {
        ConfigMall configMall = new ConfigMall();
        configMall = getInfo(configMall);
        return configMall;
    }

    private <T> T getInfo(T t) throws IllegalAccessException {
        Field[] declaredFields = t.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            String name = declaredField.getName();
            //查询并赋值
            String value = systemConfigMapper.selectByKeyName(name);
            declaredField.set(t,value);
        }
        return t;
    }

    @Override
    public ExpressConfig showExpressConfig() throws IllegalAccessException {
        ExpressConfig expressConfig = new ExpressConfig();
        expressConfig = getInfo(expressConfig);
        return expressConfig ;
    }

    @Override
    public void configExpress(ExpressConfig expressConfig) throws IllegalAccessException {
        config(expressConfig);
    }

    @Override
    public OrderConfig showOrderConfig() throws IllegalAccessException {
        OrderConfig orderConfig = new OrderConfig();
        orderConfig = getInfo(orderConfig);
        return orderConfig;
    }

    @Override
    public void configOrder(OrderConfig orderConfig) throws IllegalAccessException {
        config(orderConfig);
    }

    @Override
    public WxConfig showWxConfig() throws IllegalAccessException {
        WxConfig wxConfig = new WxConfig();
        wxConfig = getInfo(wxConfig);
        return wxConfig;
    }

    @Override
    public void configWx(WxConfig wxConfig) throws IllegalAccessException {
        config(wxConfig);
    }


    private  <T> void config(T t) throws IllegalAccessException {
        Field[] declaredFields = t.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            String name = declaredField.getName();
            String value = (String) declaredField.get(t);
            //修改操作
            SystemConfig systemConfig = new SystemConfig();
            systemConfig.setKeyName(name);
            systemConfig.setKeyValue(value);
            systemConfig.setUpdateTime(new Date());
            systemConfigMapper.updateByKeyName(systemConfig);
        }
    }

}
